package com.dcbdemo.main;

import com.dcbdemo.utils.ImageUtil;
import com.dcbdemo.utils.MysqlUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


//获取照片的主方法
public class photo_main{// 1
	// 将图片插入数据库
    public static void readImage2DB() {
        String path = "D:/image/下载3.jpg";
        Connection conn = null;
        PreparedStatement ps = null;
        FileInputStream in = null;
        String imei="869664046452895";
        try {
            in = ImageUtil.readImage(path);
            conn = MysqlUtil.getConn();
            String sql = "update 设备注册表 set 实景图=? where IMEI号='"+imei+"' ";
            ps = conn.prepareStatement(sql);
            ps.setBinaryStream(1, in, in.available());
            int count = ps.executeUpdate();
            if (count > 0) {
                System.out.println("插入成功！");
            } else {
                System.out.println("插入失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MysqlUtil.closeConn(conn);
            if (null != ps) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
    // 读取数据库中图片
    public static void readDB2Image() {   
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = MysqlUtil.getConn();
            String sql = "sql语句";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            int i=0;
            while (rs.next()) {
            	String sernumber = rs.getString("序列号");         //名称
                InputStream in = rs.getBinaryStream("注册照片");    //二进制图片
                String targetPath = "F:/image/image/"+sernumber+".jpg";//下载图片的路径
                ImageUtil.readBin2Image(in, targetPath);
                System.out.println(i+":下载成功");
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	MysqlUtil.closeConn(conn);
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    //测试
    public static void main(String[] args) throws FileNotFoundException {
    	//readImage2DB();
    	readDB2Image();
    }
}// 1
